package com.musiklegal;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class Inbox extends Activity{

	static List<InboxData> ibd=new ArrayList<InboxData>();;
	ListView lvm;
	Handler h;
	Bitmap bm =null,pic=null;
	ImageView iv,pp;
	TextView nores;
	View loading;
	
	InboxAdapter adapter;
	public void onCreate(Bundle savedInstanceState) 
    {
		h = new Handler();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.inbox);
        loading = findViewById(R.id.loadinginbox);
        nores = (TextView) findViewById(R.id.noresultinbox);
		lvm=(ListView)findViewById(R.id.inlist);
        adapter = new InboxAdapter(this,ibd);
        lvm.setAdapter(adapter);
        lvm.setOnItemClickListener(new OnItemClickListener() 
        {
          public void onItemClick(AdapterView<?> parent, View view,int position, long id) 
          {
        	  	mess(position);
        	  
          }
          });
	    

        
       
         
	     new Thread(new Runnable(){

			public void run() {
				DefaultHttpClient client = new DefaultHttpClient();  
				 HttpPost post = new HttpPost("http://secure.musiklegal.com/message/get");
				 List< BasicNameValuePair > nvps = new ArrayList< BasicNameValuePair >();
				 nvps.add(new BasicNameValuePair("USERNAME", MusikLegal.mPreferences.getString("UserName", "NoUser")));
			     nvps.add(new BasicNameValuePair("PASSWORD", MusikLegal.mPreferences.getString("PassWord", "NoUser")));
			     nvps.add(new BasicNameValuePair("MODE", "all"));
			     //Log.d("ZZZZZZZZ","Anjing");	
				 try{
					 	//Toast.makeText(getApplicationContext(), MusikLegal.mPreferences.getString("UserName", "default"), Toast.LENGTH_SHORT).show();
						
					 	UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(nvps,HTTP.UTF_8);
					 
					 	post.setEntity(p_entity);
					 	
			            HttpResponse response = client.execute(post);
			            HttpEntity responseEntity = response.getEntity();
			            
			            

			            SAXParserFactory spf = SAXParserFactory.newInstance();
			            SAXParser sp = spf.newSAXParser();
			            XMLReader xr = sp.getXMLReader();
			            //Log.d("ZZZZZZZZ","Babi");
			            InboxPar parse = new InboxPar();
			            xr.setContentHandler(parse);
			            //InputSource ins = retrieveInputStream(responseEntity);
			           // Scanner tes = new Scanner(ins.getByteStream());
			           // Log.d("tes", tes.nextLine());
			            
			            xr.parse(retrieveInputStream(responseEntity));
			            
			           h.post(new Runnable(){

						public void run() {
							loading.setVisibility(View.GONE);
							if(adapter.list.size()==0)
								nores.setVisibility(View.VISIBLE);
							
							lvm.invalidateViews();
							
						}});
			            
					
				 	}
					 catch (Exception e) {
						 
				        }
				
			}}).start();
		
		 
			 	
		        
		 
    }
	 private InputSource retrieveInputStream(HttpEntity httpEntity) {
	        InputSource insrc = null;
	        try {
	              insrc = new InputSource(httpEntity.getContent());
	        } catch (Exception e) {
	        }
	        return insrc;
	  } 
	

		void mess(final int pos)
		{
			
			
			Dialog dialog = new Dialog(this);
			
			dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
			
			LayoutInflater inflate = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View v = inflate.inflate(R.layout.readmess, (ViewGroup) findViewById(R.id.rootlayout));
        	//dialog.setTitle(ibd.get(pos).name +"\n"+ibd.get(pos).date);
        	TextView mess = (TextView) v.findViewById(R.id.textmessage),
        			title = (TextView) v.findViewById(R.id.texttitle),
        			artist = (TextView) v.findViewById(R.id.textartist),
        			sender = (TextView) v.findViewById(R.id.sender),
        			date = (TextView) v.findViewById(R.id.date),
        			time = (TextView) v.findViewById(R.id.time),
        			attch = (TextView) v.findViewById(R.id.attch);
        	sender.setText(ibd.get(pos).name);
        	String[]tgl = ibd.get(pos).date.split(" ");
        	date.setText(tgl[0]);
        	time.setText(tgl[1]);
        	pp = (ImageView) v.findViewById(R.id.pictmess);
        	
        	
        	iv =  (ImageView) v.findViewById(R.id.pict);
        	Button look =  (Button) v.findViewById(R.id.viewbutton),
        			reply = (Button) v.findViewById(R.id.replypopup);
        	
        	reply.setOnClickListener(new OnClickListener(){

				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					Send.usernameto = ibd.get(pos).username;
					startActivity(new Intent(getApplicationContext(),Send.class));
				}});
        	new Thread(new Runnable(){

				public void run() {
					// TODO Auto-generated method stub
					String pict = getPictUrl(ibd.get(pos).username);
					Log.d("uname",ibd.get(pos).username);
					Log.d("name", ibd.get(pos).name);
					Log.d("picturl", pict);
					URL url;
					
					try {
						url= new URL(pict);
						InputStream is = url.openConnection().getInputStream();
						pic = BitmapFactory.decodeStream(is);
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						pict=null;
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						pict=null;
						
					}
					h.post(new Runnable(){

						public void run() {
							// TODO Auto-generated method stub
							if(pic!=null)
								pp.setImageBitmap(pic);
							else
								pp.setImageResource(R.drawable.oc2);
						}});
					
				}}).start();
        	if(ibd.get(pos).attachment!=null)
        	{
        		new Thread(new Runnable(){

				public void run() {
					
					URL url;
					try {
						url = new URL(ibd.get(pos).attachment.album);
						
						bm = BitmapFactory.decodeStream(url.openStream());
						h.post(new Runnable(){

							public void run() {
								
								
								if(bm!=null)
									iv.setImageBitmap(bm);
								else
									iv.setImageResource(R.drawable.oc2);
								
							}});
					} catch (MalformedURLException e) {
						// TODO Auto-generated catch block
						iv.setImageResource(R.drawable.oc2);
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						iv.setImageResource(R.drawable.oc2);
						e.printStackTrace();
					}
					
					
				}}).start();
        	
        	
        	title.setText(ibd.get(pos).attachment.song);
        	artist.setText(ibd.get(pos).attachment.artist);
        	
        	look.setOnClickListener(new OnClickListener(){

				public void onClick(View arg0) {
					TrackInfo.isCatalogue=true;
					TrackInfo.fromCatalogue = true;
					TrackInfo.ds = ibd.get(pos).attachment;
					TrackInfo.mercapi = ibd.get(pos).attachment.api;
					startActivity(new Intent(Inbox.this,TrackInfo.class));
					//Toast.makeText(getApplicationContext(), ibd.get(pos).attachment.artist_id, Toast.LENGTH_SHORT).show();
				}});
        	}
        	else
        	{
        		//mess.setVisibility(View.GONE);
        		attch.setVisibility(View.GONE);
        		title.setVisibility(View.GONE);
        		artist.setVisibility(View.GONE);
        		look.setVisibility(View.GONE);
        		iv.setVisibility(View.GONE);
        	}
        	mess.setText(ibd.get(pos).mess);
		
        	dialog.setContentView(v);
        	
        	
        	//dialog.setCancelable(false);
        	/*dialog.setPositiveButton("Reply", new DialogInterface.OnClickListener() {
        	public void onClick(DialogInterface dialog, int id)
        	{
        		
        		Send.usernameto = ibd.get(pos).username;
        		startActivity(new Intent(getApplicationContext(),Send.class));
        		}
        	});
        	dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
        		public void onClick(DialogInterface dialog, int which) {
        			dialog.dismiss();
        	} });
        	dialog.setView(v);
        	dialog.create();*/
        	//dialog.setIcon(R.drawable.oc2);
            dialog.show();
		}
		
		static String getPictUrl(String uname)
		{
			String pict="";
			
			try {
				HttpClient tinfo = new DefaultHttpClient(); 
				HttpGet gets= new HttpGet("http://secure.musiklegal.com/?action=socialnet&method=friend_top_play&username="+uname);
				HttpResponse hrep = tinfo.execute(gets);
				HttpEntity trinfo = hrep.getEntity();
				SAXParserFactory spf=SAXParserFactory.newInstance();
				final FriendParser cp = new FriendParser();
				SAXParser sp=spf.newSAXParser() ;
				XMLReader xr = sp.getXMLReader();
				xr.setContentHandler(cp);
				xr.parse(new InputSource(trinfo.getContent()));
				pict = cp.packer.picture;
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ParserConfigurationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SAXException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return pict;
		}
	
}
